package org.tg.search.service.impl;


import com.baomidou.mybatisplus.core.metadata.IPage;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.GeoDistanceQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.tg.client.user.UserFeignClient;
import org.tg.model.search.LeaderEs;
import org.tg.model.user.Leader;
import org.tg.search.repository.LeaderCrudRepository;
import org.tg.search.repository.LeaderRepository;
import org.tg.search.service.LeaderService;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author Glow
 * @Date 2023-07-17 22:38:43
 * @Description
 * @Version 1.0
 */
@Service
public class LeaderServiceImpl implements LeaderService {
    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private LeaderCrudRepository leaderCrudRepository;
    @Autowired
    private LeaderRepository leaderRepository;
    @Override
    public List<LeaderEs> saveAllLeaderEs() {

        List<Leader> leaderList = new ArrayList<>();
               leaderList = userFeignClient.list();
        List<LeaderEs> leaderEsList = new ArrayList<>();
        for(int i = 0 ; i< leaderList.size(); i++)
        {
            Leader leader = leaderList.get(i);
            LeaderEs leaderEs = new LeaderEs();
            leaderEs.setId(leader.getId());
            leaderEs.setDetailAddress(leader.getDetailAddress());
            leaderEs.setDistance(new Double(0));
            leaderEs.setStorePath(leader.getStorePath());
            leaderEs.setTakeName(leader.getTakeName());
            GeoPoint geoPoint = new GeoPoint();
            geoPoint.reset(leader.getLatitude(),leader.getLongitude());
            leaderEs.setLocation(geoPoint);
           leaderEsList.add(leaderEs);
        }
        leaderCrudRepository.saveAll(leaderEsList);
        List<LeaderEs> lists = leaderCrudRepository.findAll();
        System.out.println(lists.toString());
        return lists;
    }

    @Override
    public Page<LeaderEs> getBoundLeaders(Integer page, Integer limit, Double longitude, Double latitude) {

        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        // 以某点为中心，搜索指定范围
        GeoDistanceQueryBuilder distanceQueryBuilder = new GeoDistanceQueryBuilder("location");
        distanceQueryBuilder
                .point(latitude, longitude)
                .distance(10.0, DistanceUnit.KILOMETERS);
        boolQueryBuilder.filter(distanceQueryBuilder);
        PageRequest pageRequest = PageRequest.of(page,limit);
        //查询封装
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        NativeSearchQuery build = nativeSearchQueryBuilder
                .withQuery(boolQueryBuilder)
                .withPageable(pageRequest)
                .build();
        Page<LeaderEs> leaderEsList = leaderRepository.search(build);
        //需要独立计算俩经纬度的距离，stream流忘记怎么勇了，后边优化
        List<LeaderEs> lists = leaderEsList.getContent();
        for (int i = 0 ; i< leaderEsList.getContent().size(); i++)
        {
            leaderEsList.getContent().get(i).setDistance(getDistance(longitude,latitude,leaderEsList.getContent().get(i).getLocation().getLon(),leaderEsList.getContent().get(i).getLocation().getLat())/1000);
        }
//        for(int i = 0; i < lists.size(); i++)
//        {
//            LeaderEs  leaderEs = new LeaderEs();
//                   leaderEs =  lists.get(i);
//                   //米换算成km
//            leaderEs.setDistance(getDistance(longitude,latitude,leaderEs.getLocation().getLon(),leaderEs.getLocation().getLat())/1000);
//            leaderEsList.getContent().add(leaderEs);
//        }
        return leaderEsList;
    }
//https://www.iteye.com/blog/zysnba-2426455 计算俩地理位置间距离（米）
    //地球平均半径
    private static final double EARTH_RADIUS = 6378137;
    //把经纬度转为度（°）
    private static double rad(double d){
        return d * Math.PI / 180.0;
    }
    public static double getDistance(double lng1, double lat1, double lng2, double lat2){
        double radLat1 = rad(lat1);
        double radLat2 = rad(lat2);
        double a = radLat1 - radLat2;
        double b = rad(lng1) - rad(lng2);
        double s = 2 * Math.asin(
                Math.sqrt(
                        Math.pow(Math.sin(a/2),2)
                                + Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)
                )
        );
        s = s * EARTH_RADIUS;
        s = Math.round(s * 10000) / 10000;
        return s;
    }
}
